package xyz.huanggy.minio.upload.controller;


import io.minio.errors.MinioException;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import xyz.huanggy.minio.upload.model.dto.Result;
import xyz.huanggy.minio.upload.model.dto.TaskInfoDTO;
import xyz.huanggy.minio.upload.model.entity.SysFileInfo;
import xyz.huanggy.minio.upload.model.param.InitTaskParam;
import xyz.huanggy.minio.upload.service.SysFileInfoService;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * 分片上传-分片任务记录 控制层
 */
@RestController
@RequestMapping("/v1/minio/tasks")
public class SysFileInfoController {
    /**
     * 服务对象
     */
    @Resource
    private SysFileInfoService SysFileInfoService;

    @GetMapping("/sysFileList")
    public Result<List<SysFileInfo>> sysFileList() {
        return Result.ok(SysFileInfoService.sysFileList());
    }

    /**
     * 获取上传进度
     */
    @GetMapping("/{md5}")
    public Result<TaskInfoDTO> queryProgress(@PathVariable("md5") String md5) {
        return Result.ok(SysFileInfoService.queryProgress(md5));
    }

    /**
     * 创建一个上传任务
     */
    @PostMapping
    public Result<TaskInfoDTO> initTask(@Valid @RequestBody InitTaskParam param) {

        return Result.ok(SysFileInfoService.initTask(param));
    }

    /**
     * 获取每个分片的预签名上传地址
     */
    @GetMapping("/{identifier}/{partNumber}")
    public Result<String> preSignUploadUrl(@PathVariable("identifier") String identifier, @PathVariable("partNumber") Integer partNumber) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return Result.ok(SysFileInfoService.genPreSignUploadUrl(identifier, partNumber));
    }

    /**
     * 合并分片
     */
    @PostMapping("/merge/{md5}")
    public Result<?> merge(@PathVariable String md5) {
        SysFileInfoService.merge(md5);
        return Result.ok();
    }

    @GetMapping("/download/{id}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable Long id)  {
        // 从 MinIO 下载文件
        return SysFileInfoService.downloadFile(id);

    }

}
